import re
import os
import copy
import sys
import random
# import ZoeXIBTool

class LineModel:
    def __init__(self):
        self.idStr = ''
        self.viewName = ''
        self.imgName = ''
        self.bgImgName = ''
        self.btnTypeArr = []
        # 是否已经连过线了
        self.isAdded = False
        self.isBtn = False
        self.isVC = False
        self.customClass = ''
        self.fatherViewClassName = ''





class XIBTool:
    prefixPath = ''
    allPathArr = []
    nowFileCodeArr = []
    isFindClassName = False
    nowXibTypeStr = ''
    addLineArr = []
    allImgNameArr = []
    imgNameKeyPath = ''
    imgNameValuePath = ''
    isRemoveImgBool = False
    methodNamePath = []
    nowViewClassName = ''
    def startInputData(self):


        print("确保.xib关联的.h.m文件同名且同路径，否则混淆会异常（注：若不同名只需自行更换名称保持名称一致，脚本会自动将.xib与同名的class文件关联上，无需手动关联）")

        print("拖入xib、storyboard文件夹路径（storyboard只支持替换id打乱顺序替换图片名）")

        self.prefixPath = input().strip()
        self.methodNamePath = os.path.dirname(__file__)+'/methodName.txt'
        methodNamefile = open(self.methodNamePath,'r');
        self.methodNameArray = methodNamefile.readlines()
        if(len(self.methodNameArray) == 0):
            print("error:路径下methodName.txt异常")
            return


        self.goConfusion()

    def getMethonName(self,name,maxCount):
       maxWord = random.randint(1, maxCount)
       i = 0
       newWord =''
       while i < maxWord:
           index = random.randint(0, len(self.methodNameArray)-1)
           newWord=newWord+self.methodNameArray[index].replace('\n','').replace('\r','')
           i += 1
       outputStr = name+newWord
       if maxWord == 1:
           outputStr = outputStr+self.generate_code(2)
       return outputStr


    def goConfusion(self):
        locals()
        self.allPathArr = []
        for root, dirs, files in os.walk(self.prefixPath):
            for file in files:
                path = os.path.join(root, file)
                bool = path.endswith((".storyboard",".xib"))
                # bool = path.endswith((".xib"))
                if bool == True :
                    if 'ar.lproj' in path or 'en.lproj' in path or 'tr.lproj' in path:
                        continue
                    self.allPathArr.append(path)


        self.imgNameKeyPath = os.path.dirname(__file__) + '/imgNameKey.txt'
        self.imgNameValuePath = os.path.dirname(__file__) + '/imgNameValue.txt'
        for xibPath in self.allPathArr:
            self.startScanImg(xibPath)
        unique_imgset = set(self.allImgNameArr)
        unique_imgArr = list(unique_imgset)
        newImgNameArr = []
        for imgstr in unique_imgArr:
            newImgStr = imgstr + '\n'
            newImgNameArr.append(newImgStr)
        imgKeyFile = open(self.imgNameKeyPath, 'w')
        imgKeyFile.writelines(newImgNameArr)
        imgKeyFile.close()
        imgNameValueFile = open(self.imgNameValuePath, 'w')
        imgNameValueFile.writelines(newImgNameArr)
        imgNameValueFile.close()

        print("脚本目录下已创建图片名key、value文件，若需要更改图片名前缀请替换完再继续。已完成替换（记得替换完保存关闭key、value文件，否则会影响替换）或不需要替换请输入ok继续")
        str = input().strip()
        if str != 'ok':
            print('输入错误')
            return
        self.goRpImg()

        # print("原图片名替换完成、是否移除原图片名（我会取随机字符覆盖原图片名） 需要则输入yes，不需要输入任意字符继续")
        # str = input().strip()
        # if str != 'yes':
        #     self.isRemoveImgBool = True


        index = 1
        allIndex = len(self.allPathArr)
        for xibPath in self.allPathArr:
            self.nowXibTypeStr = ''
            self.nowFileCodeArr = []
            self.addLineArr = []
            self.isFindClassName = False
            self.nowViewClassName = ''
            file_extension = os.path.splitext(xibPath)[1]
            file_name = os.path.basename(xibPath)
            file_name_without_extension = file_name.split(".")[0]
            if file_extension == '.xib':
                self.statrAddLine(xibPath)
            print(xibPath)
            self.goParse(xibPath)

            hPath = xibPath.replace('.xib', '.h')
            mPath = xibPath.replace('.xib', '.m')
            if os.path.exists(hPath) and os.path.exists(mPath):
                print('进行',file_name_without_extension,'.h  ',file_name_without_extension,'.m','连线中')
                self.goHAddline(hPath)
                self.goMAddline(mPath)

            else:
                if '/Base.lproj' in hPath and '/Base.lproj' in mPath:
                    hPath = hPath.replace('/Base.lproj','')
                    mPath = mPath.replace('/Base.lproj','')
                    if os.path.exists(hPath) and os.path.exists(mPath):
                        self.goHAddline(hPath)
                        self.goMAddline(mPath)

                    else:
                        print('未找到', file_name_without_extension, '.h或者', file_name_without_extension, '.m', '  连线失败')
                else:
                    print('未找到', file_name_without_extension, '.h或者', file_name_without_extension, '.m','  连线失败')

            print('连线中打乱顺序改id、进度%f'%(index / allIndex))
            if (index == allIndex):
                print('连线中打乱顺序改id完成')
            index = index + 1


    def goMAddline(self,mPath):
        print("s")
        locals()
        ImgSetmethodArray = []
        ImgSetmethodPath = os.path.dirname(__file__) + '/ImgSetmethod.txt'
        if os.path.exists(ImgSetmethodPath):
            ImgSetmethodfile = open(ImgSetmethodPath, 'r');
            ImgSetmethodArray = ImgSetmethodfile.readlines()
            if len(ImgSetmethodArray)  < 1:
                print('图片赋值方法数量格式不对，检查后再用')
                return
        else:
            print('图片赋值方法文件异常，检查后再用')
            return

        if len(self.addLineArr)==0:
            return


        os.chmod(mPath, 0o777)
        codefile = open(mPath, 'r');
        codeArr = codefile.readlines()
        isFind = False
        isAdd = False
        fristModel = self.addLineArr[0]
        insertIndex = 1
        setImgFuncStr = ImgSetmethodArray[0].replace('\n','')

        setImgsuffixStr = ''
        if len(ImgSetmethodArray) >= 2:
            setImgsuffixStr = ImgSetmethodArray[0].replace('\n','')
        isFunczhushi = False



        for codeStr in codeArr:
            if '@implementation' in codeStr and fristModel.fatherViewClassName in codeStr:
                isFind = True
                if '@end' in codeStr:
                    codeStr = codeStr.replace('@end','')
                    codeArr.insert(insertIndex,'@end\n')
                    isFind = False
                    if isAdd == False:
                        if fristModel.isVC == True:
                            newCodeArr = ['- (void)viewDidLoad {\n','    [super viewDidLoad];\n']
                            for model in self.addLineArr:
                                if model.isBtn == True:
                                    arr = self.getMBtnStr(model,setImgFuncStr,setImgsuffixStr)
                                    newCodeArr.extend(arr)
                                else:
                                    newCodeArr.append(self.getMImgStr(model,setImgFuncStr,setImgsuffixStr))
                            newCodeArr.append('}\n')
                        else:
                            newCodeArr = ['- (void)awakeFromNib {\n','    [super awakeFromNib];\n']
                            for model in self.addLineArr:
                                if model.isBtn == True:
                                    arr = self.getMBtnStr(model,setImgFuncStr,setImgsuffixStr)
                                    newCodeArr.extend(arr)
                                else:
                                    newCodeArr.append(self.getMImgStr(model,setImgFuncStr,setImgsuffixStr))
                            newCodeArr.append('}\n')
                        isAdd = True
                        newCodeArr.reverse()
                        for addCode in newCodeArr:
                            codeArr.insert(insertIndex-1,addCode)
                        break;
                insertIndex = insertIndex + 1
                continue

            if isFind == True:
                if '/*' in codeStr and '/*' == codeStr.replace(' ', '')[0:2]:
                    isFunczhushi = True
                    if '*/' in codeStr:
                        zIndex = codeStr.find('*/')
                        zsStr = codeStr[zIndex:].replace(' ', '').replace('\n', '')
                        if zsStr == '*/':
                            isFunczhushi = False
                    insertIndex = insertIndex + 1
                    continue

                if '*/' in codeStr and '*/' == codeStr.replace(' ', '')[0:2]:
                    isFunczhushi = False
                    insertIndex = insertIndex + 1
                    continue

                if ('//' in codeStr.replace(' ', '').replace('\n', '')[0:2]):
                    insertIndex = insertIndex + 1
                    continue
                if fristModel.isVC == True:
                    newCodestr = codeStr.replace(' ','')
                    if '[superviewDidLoad];' in newCodestr:
                        if '}' in newCodestr:
                            codeStr.replace('}','')
                            codeArr.insert(insertIndex,'}\n')
                            isFind = False
                            if fristModel.isVC == True:
                                newCodeArr = []
                                for model in self.addLineArr:
                                    if model.isBtn == True:
                                        arr = self.getMBtnStr(model, setImgFuncStr, setImgsuffixStr)
                                        newCodeArr.extend(arr)
                                    else:
                                        newCodeArr.append(self.getMImgStr(model, setImgFuncStr, setImgsuffixStr))
                            else:
                                newCodeArr = []
                                for model in self.addLineArr:
                                    if model.isBtn == True:
                                        arr = self.getMBtnStr(model, setImgFuncStr, setImgsuffixStr)
                                        newCodeArr.extend(arr)
                                    else:
                                        newCodeArr.append(self.getMImgStr(model, setImgFuncStr, setImgsuffixStr))
                            isAdd = True
                            for addCode in newCodeArr:
                                codeArr.insert(insertIndex, addCode)
                            break;
                        else:
                            isFind = False
                            if fristModel.isVC == True:
                                newCodeArr = []
                                for model in self.addLineArr:
                                    if model.isBtn == True:
                                        arr = self.getMBtnStr(model, setImgFuncStr, setImgsuffixStr)
                                        newCodeArr.extend(arr)
                                    else:
                                        newCodeArr.append(self.getMImgStr(model, setImgFuncStr, setImgsuffixStr))
                            else:
                                newCodeArr = []
                                for model in self.addLineArr:
                                    if model.isBtn == True:
                                        arr = self.getMBtnStr(model, setImgFuncStr, setImgsuffixStr)
                                        newCodeArr.extend(arr)
                                    else:
                                        newCodeArr.append(self.getMImgStr(model, setImgFuncStr, setImgsuffixStr))
                            isAdd = True
                            for addCode in newCodeArr:
                                codeArr.insert(insertIndex, addCode)
                            break;

                else:
                    newCodestr = codeStr.replace(' ', '')
                    if '[superawakeFromNib];' in newCodestr:
                        if '}' in newCodestr:
                            codeStr = codeStr.replace('}', '')
                            codeArr.insert(insertIndex, '}\n')
                            isFind = False
                            if fristModel.isVC == True:
                                newCodeArr = []
                                for model in self.addLineArr:
                                    if model.isBtn == True:
                                        arr = self.getMBtnStr(model, setImgFuncStr, setImgsuffixStr)
                                        newCodeArr.extend(arr)
                                    else:
                                        newCodeArr.append(self.getMImgStr(model, setImgFuncStr, setImgsuffixStr))
                            else:
                                newCodeArr = []
                                for model in self.addLineArr:
                                    if model.isBtn == True:
                                        arr = self.getMBtnStr(model, setImgFuncStr, setImgsuffixStr)
                                        newCodeArr.extend(arr)
                                    else:
                                        newCodeArr.append(self.getMImgStr(model, setImgFuncStr, setImgsuffixStr))
                            isAdd = True
                            for addCode in newCodeArr:
                                codeArr.insert(insertIndex, addCode)
                            break;
                        else:
                            isFind = False
                            if fristModel.isVC == True:
                                newCodeArr = []
                                for model in self.addLineArr:
                                    if model.isBtn == True:
                                        arr = self.getMBtnStr(model, setImgFuncStr, setImgsuffixStr)
                                        newCodeArr.extend(arr)
                                    else:
                                        newCodeArr.append(self.getMImgStr(model, setImgFuncStr, setImgsuffixStr))
                            else:
                                newCodeArr = []
                                for model in self.addLineArr:
                                    if model.isBtn == True:
                                        arr = self.getMBtnStr(model, setImgFuncStr, setImgsuffixStr)
                                        newCodeArr.extend(arr)
                                    else:
                                        newCodeArr.append(self.getMImgStr(model, setImgFuncStr, setImgsuffixStr))
                            isAdd = True
                            for addCode in newCodeArr:
                                codeArr.insert(insertIndex, addCode)
                            break;

                if '@end' in codeStr:
                    if isAdd == False:
                        if fristModel.isVC == True:
                            newCodeArr = ['- (void)viewDidLoad {\n', '    [super viewDidLoad];\n']
                            for model in self.addLineArr:
                                if model.isBtn == True:
                                    arr = self.getMBtnStr(model, setImgFuncStr, setImgsuffixStr)
                                    newCodeArr.extend(arr)
                                else:
                                    newCodeArr.append(self.getMImgStr(model, setImgFuncStr, setImgsuffixStr))
                            newCodeArr.append('}\n')
                        else:
                            newCodeArr = ['- (void)awakeFromNib {\n', '    [super awakeFromNib];\n']
                            for model in self.addLineArr:
                                if model.isBtn == True:
                                    arr = self.getMBtnStr(model, setImgFuncStr, setImgsuffixStr)
                                    newCodeArr.extend(arr)
                                else:
                                    newCodeArr.append(self.getMImgStr(model, setImgFuncStr, setImgsuffixStr))
                            newCodeArr.append('}\n')
                        isAdd = True
                        newCodeArr.reverse()
                        for addCode in newCodeArr:
                            codeArr.insert(insertIndex-1, addCode)
                        break;
                insertIndex = insertIndex + 1
                continue
            else:
                insertIndex = insertIndex + 1
                continue

        newFile = open(mPath, 'w')
        newFile.writelines(codeArr)
        newFile.close()










    def getMImgStr(self,model,setImgFuncStr,setImgsuffixStr):
        locals()
        str = ('[self.{} setImage:{}];\n'.format(model.viewName, setImgFuncStr))
        imgName = ('{}{}'.format(model.imgName, setImgsuffixStr))
        str = str.replace('---替换符---', imgName)
        return str

    def getMBtnStr(self,model,setImgFuncStr,setImgsuffixStr):
        locals()

        btnArr = []
        for dic in model.btnTypeArr :
            str = ''
            if 'image' in dic:
                 if dic['key'] == 'normal':
                     str = ('[self.{} setImage:{}  forState:UIControlStateNormal];\n'.format(model.viewName,setImgFuncStr))
                     imgName = ('{}{}'.format(dic['image'],setImgsuffixStr))
                     str = str.replace('---替换符---',imgName)

                 elif dic['key'] == 'disabled':
                     str = ('[self.{} setImage:{}  forState:UIControlStateDisabled];\n'.format(model.viewName,setImgFuncStr))
                     imgName = ('{}{}'.format(dic['image'],setImgsuffixStr))
                     str = str.replace('---替换符---',imgName)

                 elif dic['key'] == 'selected':
                     str = ('[self.{} setImage:{}  forState:UIControlStateSelected];\n'.format(model.viewName,setImgFuncStr))
                     imgName = ('{}{}'.format(dic['image'], setImgsuffixStr))
                     str = str.replace('---替换符---',imgName)

                 elif dic['key'] == 'highlighted':
                     str = ('[self.{} setImage:{}  forState:UIControlStateHighlighted];\n'.format(model.viewName,setImgFuncStr))
                     imgName = ('{}{}'.format(dic['image'], setImgsuffixStr))
                     str = str.replace('---替换符---',imgName)
            else:
                if dic['key'] == 'normal':
                    str = ('[self.{} setBackgroundImage:{}  forState:UIControlStateNormal];\n'.format(model.viewName, setImgFuncStr))
                    imgName = ('{}{}'.format(dic['backgroundImage'], setImgsuffixStr))
                    str = str.replace('---替换符---', imgName)

                elif dic['key'] == 'disabled':
                    str = ('[self.{} setBackgroundImage:{}  forState:UIControlStateDisabled];\n'.format(model.viewName,setImgFuncStr))
                    imgName = ('{}{}'.format(dic['backgroundImage'], setImgsuffixStr))
                    str = str.replace('---替换符---', imgName)

                elif dic['key'] == 'selected':
                    str = ('[self.{} setBackgroundImage:{}  forState:UIControlStateSelected];\n'.format(model.viewName,setImgFuncStr))
                    imgName = ('{}{}'.format(dic['backgroundImage'], setImgsuffixStr))
                    str = str.replace('---替换符---', imgName)

                elif dic['key'] == 'highlighted':
                    str = ('[self.{} setBackgroundImage:{}  forState:UIControlStateHighlighted];\n'.format(model.viewName,setImgFuncStr))
                    imgName = ('{}{}'.format(dic['backgroundImage'], setImgsuffixStr))
                    str = str.replace('---替换符---', imgName)
            btnArr.append(str)
        return btnArr





    def goHAddline(self,hPath):
        locals()
        os.chmod(hPath, 0o777)
        codefile = open(hPath, 'r');
        codeArr = codefile.readlines()
        isFunczhushi = False
        newCodeArr = copy.deepcopy(codeArr)

        if len(self.addLineArr)>0:
            fristModel = self.addLineArr[0]
            insertIndex = 1
            for codeStr in codeArr:
                if '/*' in codeStr and '/*' == codeStr.replace(' ', '')[0:2]:
                    isFunczhushi = True
                    if '*/' in codeStr:
                        zIndex = codeStr.find('*/')
                        zsStr = codeStr[zIndex:].replace(' ', '').replace('\n', '')
                        if zsStr == '*/':
                            isFunczhushi = False
                    insertIndex = insertIndex + 1
                    continue
                if '*/' in codeStr and '*/' == codeStr.replace(' ', '')[0:2]:
                    isFunczhushi = False
                    insertIndex = insertIndex + 1
                    continue

                if '@interface' in codeStr and fristModel.fatherViewClassName in codeStr and isFunczhushi == False:
                    if ('//' in codeStr.replace(' ', '').replace('\n', '')[0:2]):
                        insertIndex = insertIndex + 1
                        continue

                    if "@end" in codeStr:
                        codeStr = codeStr.replace('@end','')
                        codeArr. insert(insertIndex,"@end\n")
                        for model in self.addLineArr:
                            if model.isAdded == False:
                                codeArr.insert(insertIndex,self.getInHPStr(model))
                        break

                    for model in self.addLineArr:
                        if model.isVC == True:
                            if 'UIButton' in codeStr \
                                    or 'UIView' in codeStr \
                                    or 'UIImageView' in codeStr or 'UICollectionViewCell' in codeStr \
                                    or 'UITableViewCell' in codeStr \
                                    or 'UILabel' in codeStr \
                                    or 'UITextField' in codeStr \
                                    or 'UITextView' in codeStr:
                                if 'UIViewController' in codeStr:
                                     model.isVC = True
                                else:
                                    model.isVC = False

                        if model.isAdded == False:
                            codeArr.insert(insertIndex, self.getInHPStr(model))

                    break
                insertIndex = insertIndex + 1

            newFile = open(hPath, 'w')
            newFile.writelines(codeArr)
            newFile.close()


    def getInHPStr(self,model):
        locals()
        str = ''
        if model.isBtn == True:
            str = ('@property (weak, nonatomic) IBOutlet UIButton *{};\n'.format(model.viewName))

        else:
            str = ('@property (weak, nonatomic) IBOutlet UIImageView *{};\n'.format(model.viewName))
        return str



    def goParse(self, xibPath):
        locals()
        os.chmod(xibPath, 0o777)
        codefile = open(xibPath, 'r');
        # codeArr = codefile.readlines()
        codeText = codefile.read()
        idArr = self.extract_quotes(codeText)
        unique_idset = set(idArr)
        unique_idArr = list(unique_idset)
        newIdArr = []
        for id in unique_idArr:
            newIdArr.append(self.getNewId())
        for index in range(0,len(unique_idArr)):
            codeText = codeText.replace(unique_idArr[index],newIdArr[index])

        PInTagArr = self.getPInTagArr(codeText)
        NewPInTagArr = self.getNewPInTagArr(PInTagArr)

        for index in range(0,len(PInTagArr)):
            codeText = codeText.replace(PInTagArr[index], NewPInTagArr[index])

        annotationArr = re.findall(r'<!--.*?-->', codeText)
        for index in range(0,len(annotationArr)):
            codeText = codeText.replace(annotationArr[index], '')

        newFile = open(xibPath, 'w')
        newFile.write(codeText)
        newFile.close()

    def extract_quotes(self,text):
        pattern = r'id="(.*?)"'  # 匹配双引号之间的内容
        result = re.findall(pattern, text)
        sceneIDpattern = r'sceneID="(.*?)"'  # 匹配双引号之间的内容
        sceneIDRes = re.findall(sceneIDpattern, text)
        newsceneIDRes = list(filter(self.checkIdType,sceneIDRes))
        newRusult = list(filter(self.checkIdType,result))
        newRusult.extend(newsceneIDRes)
        return newRusult
    def getPInTagArr(self,text):
        annotationArr = re.findall(r'<!--.*?-->', text)
        for index in range(0,len(annotationArr)):
            text = text.replace(annotationArr[index], '')
        result = re.findall(r'<.*? (.*?)\?*/*>', text)
        return result
    def getNewPInTagArr(self,arr):
        newArr = []
        for PInTagText in arr:
            res = re.findall(r'[^=]+="[^"]*"', PInTagText)
            if 'encoding="UTF-8"' not in PInTagText:
                random.shuffle(res)
            newResArr =[]
            for newText in res:
                if len(newText)>0:
                    newResArr.append(newText)
            str = ' '.join(newResArr)
            newArr.append(str)
        return newArr

    def checkIdType(self,text):
        regex = r'[A-Za-z0-9]{3}-[A-Za-z0-9]{2}-[A-Za-z0-9]{3}'
        if re.fullmatch(regex, text):
            return True
        else:
            return False





    def startScanImg(self,xibPath):
        locals()
        os.chmod(xibPath, 0o777)
        codefile = open(xibPath, 'r');
        codeText = codefile.read()
        imgArr = self.getImgStrArr(codeText)
        self.allImgNameArr.extend(imgArr)


    def getImgStrArr(self,text):
        pattern = r'image="(.*?)"'  # 匹配双引号之间的内容
        result = re.findall(pattern, text)

        imgPattern = r'backgroundImage="(.*?)"'  # 匹配双引号之间的内容
        imgResult = re.findall(imgPattern, text)

        result.extend(imgResult)
        return result

    def goRpImg(self):
        locals()
        self.allPathArr = []
        for root, dirs, files in os.walk(self.prefixPath):
            for file in files:
                path = os.path.join(root, file)
                bool = path.endswith((".storyboard",".xib"))
                # bool = path.endswith((".xib"))


                if bool == True:
                    if 'ar.lproj' in path or 'en.lproj' in path or 'tr.lproj' in path:
                        continue
                    self.allPathArr.append(path)
        index = 1
        allIndex = len(self.allPathArr)
        for xibPath in self.allPathArr:
            print(xibPath)
            self.goImgParse(xibPath)
            print('图片名替换进度%f'%(index / allIndex))
            if (index == allIndex):
                print('图片名更换完成')
            index = index + 1
    def goImgParse(self,xibPath):
        locals()
        os.chmod(xibPath, 0o777)
        codefile = open(xibPath, 'r');
        codeText = codefile.read()
        keyImgfile = open(self.imgNameKeyPath, 'r');
        valueImgfile = open(self.imgNameValuePath, 'r');
        keyImgArr = keyImgfile.readlines()
        valueImgArr = valueImgfile.readlines()

        if (len(keyImgArr) == len(valueImgArr)):
            for index in range(0, len(keyImgArr)):
                codeText = codeText.replace(keyImgArr[index].strip(), valueImgArr[index].strip())
                newFile = open(xibPath, 'w')
                newFile.write(codeText)
                newFile.close()
        else:
            print('key value数目不一致请检查后再替换')


    def startInsertXibLine(self,xibPath):
        locals()
        PList = []
        if (len(self.addLineArr) > 0):
            for any in self.nowFileCodeArr:
                if type(any) == dict:
                    PList = list(any['Property'])
                    break
            if len(PList) > 0:
                addPArr = []
                for model in self.addLineArr:
                    model.fatherViewClassName = self.nowViewClassName
                    isFind = False
                    for PcodeStr in PList:
                        if model.idStr in PcodeStr:
                            Pattern = r'property="(.*?)"'  # 匹配双引号之间的内容
                            result = re.findall(Pattern, PcodeStr)
                            model.viewName = result.pop()
                            model.isAdded = True
                            isFind = True
                            break
                    if isFind == False:
                        pNewStr = self.creatNewPropertyCoede(model)
                        addPArr.append(pNewStr)
                PList.extend(addPArr)
                any['Property'] = PList
            else:
                addPArr = ['<connections>\n']
                for model in self.addLineArr:
                    pNewStr = self.creatNewPropertyCoede(model)
                    addPArr.append(pNewStr)
                addPArr.append('</connections>\n')
                if self.nowXibTypeStr == "VC":
                    insertIndex = 1
                    for codeText in self.nowFileCodeArr:
                        if 'userLabel=\"File\'s Owner\"' in codeText:
                            codeText = codeText.replace('/','')
                            break
                        insertIndex = insertIndex + 1
                        addPArr.append('</placeholder>\n')
                    self.nowFileCodeArr.insert(insertIndex, {'Property':addPArr})
                else:
                    insertIndex = 1+1
                    for codeText in self.nowFileCodeArr:
                        if 'customClass="UIResponder"' in codeText:
                            break
                        insertIndex = insertIndex + 1
                    self.nowFileCodeArr.insert(insertIndex, {'Property':addPArr})


        newFileCodeArr = []
        for any in self.nowFileCodeArr:
            if type(any) == dict:
                newPList = list(any['Property'])
                newFileCodeArr.extend(newPList)
            else:
                newFileCodeArr.append(any)
        newFile = open(xibPath, 'w')
        newFile.writelines(newFileCodeArr)
        newFile.close()





    def creatNewPropertyCoede(self,model):
        model.viewName = self.getMethonName('',3)
        model.isAdded = False
        str = ('<outlet property="{}" destination="{}" id="{}"/>\n'.format(model.viewName, model.idStr,self.getNewId()))

        return str
    def generate_code(self,code_len=4):
        all_charts = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
        last_pos = len(all_charts) - 1
        code = ''
        for _ in range(code_len):
            index = random.randint(0, last_pos)
            code += all_charts[index]
        return code
    def getNewId(self):
        newId = self.generate_code(3)+'-'+self.generate_code(2)+'-'+self.generate_code(3)
        return newId



    def statrAddLine(self,xibPath):
        locals()
        isBtn = False
        isImgView = False
        isProperty = False
        PropertyArr = []
        isResources = False
        ResourcesArr = []
        addLineModel = LineModel()
        oldName = ""
        os.chmod(xibPath, 0o777)
        codefile = open(xibPath, 'r');
        codeArr = codefile.readlines()
        file_extension = os.path.splitext(xibPath)[1]
        file_name = os.path.basename(xibPath)
        file_name_without_extension = file_name.split(".")[0]
        for codeStr in codeArr:
            if file_extension == '.xib':
                oldName = self.findXibClassName(codeStr,self.isFindClassName)
                if len(oldName) > 0:
                    self.nowViewClassName = oldName
                    codeStr = codeStr.replace(oldName,file_name_without_extension)
            else:
                oldName = self.findSBClassName(codeStr,self.isFindClassName)

            if isBtn == True :
                self.nowFileCodeArr.append(codeStr)
                if 'image=' in codeStr:
                    imgPattern = r'image="(.*?)"'  # 匹配双引号之间的内容
                    imgresult = re.findall(imgPattern, codeStr)
                    keyPattern = r'key="(.*?)"'  # 匹配双引号之间的内容
                    keyresult = re.findall(keyPattern, codeStr)
                    if len(imgresult)>0 and len(keyresult)>0:
                        imgDic = {'key': keyresult.pop(), 'image': imgresult.pop()}
                        addLineModel.btnTypeArr.append(imgDic)
                if 'backgroundImage="' in codeStr:
                    imgPattern = r'backgroundImage="(.*?)"'  # 匹配双引号之间的内容
                    imgresult = re.findall(imgPattern, codeStr)
                    keyPattern = r'key="(.*?)"'  # 匹配双引号之间的内容
                    keyresult = re.findall(keyPattern, codeStr)
                    if len(imgresult)>0 and len(keyresult)>0:
                        imgDic = {'key': keyresult.pop(), 'backgroundImage': imgresult.pop()}
                        addLineModel.btnTypeArr.append(imgDic)
                if '/button>' in codeStr:
                    if len(addLineModel.btnTypeArr) > 0:
                        self.addLineArr.append(copy.deepcopy(addLineModel))
                    addLineModel = LineModel()
                    isBtn = False
                    continue
            elif isImgView == True:
                self.nowFileCodeArr.append(codeStr)
                if '/imageView>' in codeStr:
                    if len(addLineModel.imgName) > 0:
                        self.addLineArr.append(copy.deepcopy(addLineModel))
                    addLineModel = LineModel()
                    isImgView = False
                    continue
            elif isProperty == True:
                checkCode = codeStr.replace(" ",'')
                if 'outlet' in checkCode and 'property='in checkCode:
                    PropertyArr.append(codeStr)
                    continue
                if '</connections>' in  checkCode:
                    isProperty = False
                    if (len(PropertyArr)>0):
                        self.nowFileCodeArr.append({"Property":PropertyArr})
                    PropertyArr = []
                    self.nowFileCodeArr.append(codeStr)
                    continue
                self.nowFileCodeArr.append(codeStr)

            elif isResources == True:
                self.nowFileCodeArr.append(codeStr)
            else:
                self.nowFileCodeArr.append(codeStr)
                if '<connections' in codeStr:
                    isProperty = True
                    if '/connections>' in codeStr:
                        isProperty = False
                    continue
                elif '<resources'in codeStr:
                    isResources = True
                    if '/resources>' in codeStr:
                        isResources = False
                    continue
                elif '<button' in codeStr:
                    isBtn = True
                    pattern = r'id="(.*?)"'  # 匹配双引号之间的内容
                    result = re.findall(pattern, codeStr)
                    addLineModel.isBtn = True
                    if self.nowXibTypeStr == "VC":
                        addLineModel.isVC = True
                    else:
                        addLineModel.isVC = False

                    if 'customClass=' in codeStr:
                        cCpattern = r'customClass="(.*?)"'  # 匹配双引号之间的内容
                        cCresult = re.findall(cCpattern, codeStr)
                        addLineModel.customClass = cCresult.pop()


                    if (len(result)>0):
                        addLineModel.idStr = result.pop()
                    if '/button>' in codeStr:
                        if len(addLineModel.btnTypeArr)>0:
                            self.addLineArr.append(copy.deepcopy(addLineModel))
                        addLineModel = LineModel()
                        isBtn = False
                        continue
                elif '<imageView' in codeStr:
                    isImgView = True
                    pattern = r'id="(.*?)"'  # 匹配双引号之间的内容
                    result = re.findall(pattern, codeStr)
                    addLineModel.isBtn = False
                    if self.nowXibTypeStr == "VC":
                        addLineModel.isVC = True
                    else:
                        addLineModel.isVC = False
                    if 'customClass=' in codeStr:
                        cCpattern = r'customClass="(.*?)"'  # 匹配双引号之间的内容
                        cCresult = re.findall(cCpattern, codeStr)
                        addLineModel.customClass = cCresult.pop()

                    if (len(result) > 0):
                        addLineModel.idStr = result.pop()
                    if 'image=' in codeStr:
                        imgPattern = r'image="(.*?)"'  # 匹配双引号之间的内容
                        imgresult = re.findall(imgPattern, codeStr)
                        if len(imgresult) > 0 :
                            addLineModel.imgName = imgresult.pop()
                    if '/imageView>' in codeStr:
                        if len(addLineModel.imgName) > 0:
                            self.addLineArr.append(copy.deepcopy(addLineModel))
                        addLineModel = LineModel()
                        isImgView = False
                        continue

        self.startInsertXibLine(xibPath)




    def findXibClassName(self,codeStr,isFindClassName):
        locals()
        if isFindClassName == False:
            if "customClass=" in codeStr:
                pattern = r'customClass="(.*?)"'  # 匹配双引号之间的内容
                result = re.findall(pattern, codeStr)
                for classStr in result:
                    if classStr == 'UIResponder':
                         return ''
                    else:
                         self.isFindClassName = True
                         if 'userLabel=\"File\'s Owner\"' in codeStr:
                             self.nowXibTypeStr = "VC"
                         else:
                             newPattern = r'<(.*?) '  # 匹配双引号之间的内容
                             newResult = re.findall(newPattern, codeStr)
                             if len(newResult) > 0:
                                 self.nowXibTypeStr = newResult.pop()
                         return classStr
            else:
                return ''
        else:
            return ''





    def findSBClassName(self,codeStr,isFindClassName):
        return ''











newxib = XIBTool()
newxib.startInputData()
# xib = ZoeXIBTool.XibTool()
